<style type="text/css">
#addUserGroupForm-cont ul {
    margin: 0;
    padding: 0;
    max-height: 300px;
    overflow: auto;
}
#addUserGroupForm-cont ul li {
    float: none;
    margin: 0;
    padding: 0;
    background: none;
    cursor: default;
    border: none;
    box-shadow: none;
}
.addUserGroupForm-rename {
    width: 100%;
}
#addUserGroupForm-cont .hidden {
    display: none;
}
#addUserGroupForm-cont .form-actions * {
    float: left;
}
#addUserGroupForm-cont .form-actions input[type=text] {
    float: left;
    width: 140px;
    margin: 0 3px 0 0;
}
#addUserGroupForm-cont .form-actions select {
    width: 210px;
    margin: 0 3px 0 0;
}
#addUserGroupForm-submit{
    margin: 0 3px 0 0;
}
.ui-dialog h2.errorLog {
    margin: 0 0 15px 0;
    color: #AA0004;
    font-size: 1.2em;
    font-weight: bold;
}
</style>

<div id="addUserGroupForm-cont" class="hidden">
    <form class="well form-inline margin-horisontal" action="javascript:void(0);" method="POST" name="addUserGroupForm" id="addUserGroupForm">
        <h2 class="errorLog hidden"></h2>
        <!-- <fieldset>
          <label for="name">Имя</label>
          <input name="name" type="text" value=""/>
        </fieldset> -->
        <div class="form-actions">
          <button type="submit" class="btn btn-primary" id="addUserGroupForm-submit">
            <i class="icon-ok icon-white"></i>&ensp;<span>OK</span>
          </button>
          <button type="reset" class="btn btn-danger" id="addUserGroupForm-cancel">
            <i class="icon-remove icon-white"></i>&ensp;<span>Отменить</span>
          </button>
        </div>
    </form>
</div>

<script type="text/javascript" language="javascript">

function userRenderGroupSelector(groups) {
    var elements = $('<select name="groups">').append(
        $('<option>').attr({ value: null, selected: "selected" }).text('Выберите группу'),
        $('<option>').attr({ value: 0 }).text('Новая группа')
    );
    for(var i in groups){
        var g = groups[i];
        elements.append(
            $('<option>').attr({ value: g.id }).text(g.filter_name)
        );
    }
    elements = elements.add(
      $('<input type="text" class="newgroup" />').addClass('hidden')
    );
    return elements;
}
function userItemClick(elm) {
    var userId = [];
    if (!isCtrl) {
        $('#usersGroups').find('.selected').each(function(){
            $(this).removeClass('selected');
            userId.push(
                Number($(this).attr('id').replace('user-cell-',''))
            );
        });
        if (userId.length > 1) {
            Elm.groupForm.children('form').data({
                action: 'move',
                users: userId
            });
            userId = null;
            Elm.groupForm.dialog('open');
            return false;
        }
        elm = elm || { id:false };
        userId = [ elm.id.replace('user-cell-','') ];
        Elm.groupForm.children('form').data({
                action: 'move',
                users:  userId
        });
        userId = null;
        Elm.groupForm.dialog('open');
        /*if (!userId) return false;
        openUserAccessDialog(userId[0], function(cdata) {
            // refresh
        });*/
    } else {
        if ($(elm).hasClass('selected')) $(elm).removeClass('selected');
        else $(elm).addClass('selected');
    }
    return false;
}
Elm.groupForm = $('#addUserGroupForm-cont').dialog({
          autoOpen:   false,
          width:      450,
          modal:      true,
          draggable:  true,
          resizable:  false,
          stack:      true,
          open: function(event, ui){
            var form = $(this).children('form');
            $(this).find('.errorLog').addClass('hidden');
            switch (form.data('action')) {

              case 'move':
                    $(this).dialog('option', 'title',  'Переместить');
                    form.find('button[type=submit]').addClass('disabled').button("disable").children('span').text('Переместить');
                    form.find('button[type=reset]').addClass('hidden');
                    var groupSelector = userRenderGroupSelector(Elm.Groups);
                        groupSelector.prependTo(form.children('.form-actions')).focus();
                        form.find('select[name=groups]').change(function(){
                            var v = Number($(this).children('option:selected').val());
                            if (v > 0) form.find('button[type=submit]').removeClass('disabled').button("enabled");
                            else {
                                $(this).addClass('hidden');
                                $(this).next('input[type=text]').removeClass('hidden').focus().val('');
                                $('#addUserGroupForm-cancelnew').removeClass('hidden');
                                form.find('button[type=submit]').addClass('disabled').button('disable');
                                // if (v == 0) form.find('button[type=submit]').removeClass('disabled').button('enabled');
                            }
                        });
                        groupSelector.next('input[type=text]')
                            .keydown(function(event) {
                                if($(this).val().length > 0){
                                    form.find('button[type=submit]').removeClass('disabled').button('enabled');
                                    form.data('groupName', $(this).val());
                                }
                                else {
                                    form.find('button[type=submit]').addClass('disabled').button('disable');
                                    form.data('groupName', null);
                                }
                             }).blur(function(e) {
                                if($(this).val().length > 0) {
                                    form.find('button[type=submit]').removeClass('disabled').button('enabled');
                                    form.data('groupName', $(this).val());
                                }
                                else {
                                    form.find('button[type=submit]').addClass('disabled').button('disable');
                                    form.data('groupName', null);
                                }
                            });
                        form.children('.form-actions').append(
                            $('<button type="reset" id="addUserGroupForm-cancelnew" class="btn btn-danger" />')
                                .addClass('hidden')
                                .html('<span>Отмена</span>')
                        );
                        $('#addUserGroupForm-cancelnew').click(function(){
                            groupSelector.removeClass('hidden').focus();
                            groupSelector.next('input[type=text]').addClass('hidden').val('');
                            $('#addUserGroupForm-cancelnew').addClass('hidden');
                            form.find('button[type=submit]').addClass('disabled').button('disable');
                        });
                    var userCell = $('<ul>');
                    $.each(form.data('users'), function(i, id){
                        userCell.append( $('#user-cell-' + id).clone() );
                    });
                    userCell.prependTo(form);
                    break;

               case 'rename':
                    $(this).dialog('option', 'title',  'Переименовать группу');
                    form.prepend($('<input type="text" class="addUserGroupForm-rename" />').val(
                       Elm.Groups[ form.data('group') ].filter_name
                    ));
                    // console.log(Elm.Groups);
                    // console.log(Elm.Users);
                    form.find('button[type=reset]').addClass('hidden');
                    form.find('button[type=submit]').css({ float: 'right' }).children('span').text('Переименовать');
                    break;

               case 'delete':
                    $(this).dialog('option', 'title',  'Удалить группу');
                    form.prepend($('<h2/>').addClass('errorLog').text(
                        Elm.Groups[ form.data('group') ].filter_name
                    ));
                    form.find('button[type=submit]').children('span').text('Удалить');
                    break;
            }
          },
          close: function(){
            var form = $(this).children('form');
            form.data({
                action: false,
                users:  null,
                group:  null,
                groupName: null
            });
            form.children('ul').remove();
            form.children('.form-actions').children('select').remove();
            form.children('.form-actions').children('input[type=text]').remove();
            form.children('.errorLog').remove();

            form.find('.addUserGroupForm-rename').remove();
            $('#addUserGroupForm-cancelnew').remove();
            form.find('button[type=submit]').css({ float: 'left' }).removeClass('disabled').button("enabled").children('span').text('OK');
            form.find('button[type=reset]').removeClass('hidden');
          }
      }).removeClass('hidden');
/*Elm.groupForm.find('button[type=submit]').click(function(){
        Elm.groupForm.submit();
});*/
Elm.groupForm.submit(function(e){
    var form = $(e.target);
    if (!form.find('button[type=submit]').hasClass('disabled')) {
        userGroup_dataSubmit(form);
    }
});

function userGroup_dataSubmit(d){
        var action = d.data('action'),
            data   = null;
         switch (action) {
            case 'move':
                    data = {
                        action:    null,
                        users:     d.data('users'),
                        groupId:   Number(d.children('.form-actions').children('select').children('option:selected').val()),
                        groupName: d.data('groupName')
                    };
                    if (data.groupId > 0) data.action = '<?php echo ACTIONS::USERS_MOVE_USER; ?>';
                    else data.action = '<?php echo ACTIONS::USERS_CREATE_GROUP; ?>';
                break;
            case 'rename':
                    data = {
                        action:    '<?php echo ACTIONS::USERS_RENAME_GROUP; ?>',
                        users:     d.data('users'),
                        groupId:   d.data('group'),
                        groupName: d.find('input.addUserGroupForm-rename').val()
                    };
                break;
            case 'delete':
                    data = {
                        action:    '<?php echo ACTIONS::USERS_DELETE_GROUP; ?>',
                        groupId:   Number(d.data('group'))
                    };
                break;
        }
        jsonRequest(
            'users.php', data,
            // onSuccess
            function(data){
                var chs = checkSession(data);
                if(!chs) {
                  Elm.loginFormModal.dialog('open');
                  return false;
                }
                userGroup_dataOnsuccess();
            },
            // onError
            function(data){ console.error(data.message); }
        );
}


function userGroup_datass() { $('#usersListCont').triggerHandler('userDataSuccess'); }
function loadUList() {
    Elm.groupForm.dialog('close');
    $('#usersListCont').empty();
    loadUsersList();
}

$('#usersListCont').bind('userDataSuccess', function(event, data) {

    $(".thumbnails li[id^='user-cell']")
        .removeAttr('onclick')
        .click(function(){ userItemClick(this) })
        .mouseover(function(){  if (isShift) { $(this).addClass('selected') }  });

    $('.addUserGroupForm-groupRename').parent('div[style*=right]').remove();
    $('ul.thumbnails').each(function(){

        var id = Number($(this).attr('id').replace('userGroupUsers-',''));

        if (id > 1) $(this).append(

                $('<button type="submit" class="btn btn-primary addUserGroupForm-groupRename">').css({ margin: '0 5px 0 0' })
                    .click(function(){
                        Elm.groupForm.children('form').data({ action: 'rename', group:  id });
                        Elm.groupForm.dialog('open');
                    }).html('<i class="icon-pencil icon-white"></i>&ensp;<span>Переименовать группу</span>'),

                $('<button type="reset" class="btn btn-danger addUserGroupForm-groupDelete">').click(function(){
                        Elm.groupForm.children('form').data({ action: 'delete', group:  id });
                        Elm.groupForm.dialog('open');
                    }).html('<i class="icon-remove icon-white"></i>&ensp;<span>Удалить группу</span>')
        );
        $(this).find('button').wrapAll(  $('<li>').css({
            float:         'center',
            'white-space': 'normal',
            'text-align':  'right'
        })  );
    });
});

function userGroup_dataOnsuccess() { loadUList(); }



var isCtrl  = false, isShift = false;

$(function() {
    Elm.groupForm.find('button[type=reset]').click(function(){
        Elm.groupForm.dialog('close');
    });
    
    $(document).keyup(function (e) {
              if(e.which == 17) isCtrl  = false;
              if(e.which == 16) isShift = false;
    }).keydown(function (e) {
              if(e.which == 17) isCtrl  = true;
              if(e.which == 16) isShift = true;
              if(e.which == 83 && isCtrl == true) return false;
    });
});

$(function() {
    $('.nav-list .active a').each(function(){
        $('.pageTitle').text($(this).text());
    });
});

</script>
